#pragma once
#include "Common.hpp"
#include <set>
#include <cstdio>
//一个简易的xshell，为了安全考虑，只能使用限定的命令
class Command
{
public:
    Command()
    {
        _WhiteListCommand.insert("ls -a");
        _WhiteListCommand.insert("whoami");
        _WhiteListCommand.insert("pwd");
        _WhiteListCommand.insert("cd ..");
        _WhiteListCommand.insert("touch 1.txt");
        _WhiteListCommand.insert("rm -rf 1.txt");
    }
    bool IsSafe(const std::string& cmd)
    {
        auto it=_WhiteListCommand.find(cmd);
        return it!=_WhiteListCommand.end();
    }
    
    std::string Excute(const std::string& cmd,InetAddr&addr)
    {
        if(!IsSafe(cmd))return std::string("UnSafe Command");
        
        std::string who=addr.StringAddr();
        FILE* fp=popen(cmd.c_str(),"r");
        if(fp==nullptr)
        {
            return std::string("这条命令不存在：")+cmd;
        }
        std::string res;
        char line[1024];
        while(fgets(line,sizeof line,fp))
        {
            res+=line;
        }
        pclose(fp);
        std::string result=who+"execute done,result is: \n"+res;
        LOG(DEBUG)<<result;
        return result;
    }

    ~Command(){}
private:
    std::set<std::string> _WhiteListCommand;
};